//
//  VideoListViewController.m
//  clublbiza
//
//  Created by WANG TOM on 7/29/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "VideoListViewController.h"
#import "TMDataTable.h"
#import "clublbizaAppDelegate.h"
#import "Catalog_sub.h"
#import "Catalog_sub_video.h"
#import "Resource.h"
#import "PlayViewController.h"

#define ITEM_PAGE_SIZE 5

@interface VideoListViewController ()

@end

@implementation VideoListViewController
@synthesize recordView;
@synthesize titleView;
@synthesize pageIndex;
@synthesize subCatalogUUID;
@synthesize seperatorView;
@synthesize subTitleView;
@synthesize previousButton;
@synthesize nextButton;
@synthesize pageInfoView;
@synthesize mainBackgroundImage;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.
    //Init catalog title
    [self refreshBackGrounImage];
     AppMain *appMain = [AppMain shareInstance];
   clublbizaAppDelegate *appDelegate = (clublbizaAppDelegate *)[[UIApplication sharedApplication] delegate];
    TMDataTable *dt = [[TMDataTable alloc] initWithTablename:@"Catalog_sub" withPKName:@"uuid" contextProvider:appDelegate];
    
    Catalog_sub *subCatalogData = (Catalog_sub*)[dt findByField:@"version_id" withValue:[NSNumber numberWithInt:appMain.currentSelectedSubCatalogVersionId] withSort:nil];
    
    self.titleView.text = subCatalogData.name;
    self.subTitleView.text = subCatalogData.sub_name;
    self.subCatalogUUID = subCatalogData.uuid;
    

    self.pageIndex = 0;
    
    //set color
    [self.seperatorView setBackgroundColor:[UIColor colorWithRed:0 green:255 blue:255 alpha:1.0]];
    [self.titleView setTextColor:[UIColor colorWithRed:0 green:255 blue:255 alpha:1.0]];
    [self.subTitleView setTextColor:[UIColor colorWithRed:0 green:255 blue:255 alpha:1.0]];
    [self.pageInfoView setTextColor:[UIColor colorWithRed:0 green:255 blue:255 alpha:1.0]];
    
    [dt release];
    [self refreshDataListView];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    
    [self releaseRetainResourc];
    
}
- (void) releaseRetainResourc
{
    self.recordView = nil;
    self.titleView = nil;
    self.seperatorView = nil;
    self.subTitleView = nil;
    self.previousButton = nil;
    self.nextButton = nil;
    self.pageInfoView = nil;
    self.mainBackgroundImage = nil;
    
    [self.subCatalogUUID release];
   
    NSLog(@"video list unload");
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	 return interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight;
}

-(IBAction)backSubCatalogList:(id)sender
{
    [self.subCatalogUUID release];
    [self.navigationController popViewControllerAnimated:YES];

}

- (void) refreshDataListView
{
    //Remove all item views
    NSArray *subviews = [[self.recordView subviews] copy];
    for (UIView *subview in subviews) {
        [subview removeFromSuperview];
    }
    [subviews release];
    
    clublbizaAppDelegate *appDelegate = (clublbizaAppDelegate *)[[UIApplication sharedApplication] delegate];
   // appMain.currentSelectedSubCatalogVersionId
    TMDataTable *dtVideo = [[TMDataTable alloc] initWithTablename:@"Catalog_sub_video" withPKName:@"uuid" contextProvider:appDelegate];
    
    NSString *condition = [NSString stringWithFormat:@"sub_catalog_uuid='%@' AND active=1", self.subCatalogUUID ];
    NSArray *videoListAll = [dtVideo findAll:condition withSort:@"order"];
    
   
    int item_index = self.pageIndex*ITEM_PAGE_SIZE;
    int end_index = item_index + ITEM_PAGE_SIZE;
    if ( end_index > videoListAll.count)
    {
        end_index = videoListAll.count;
    }
    int i = 0;
    TMDataTable *dtResource = [[TMDataTable alloc] initWithTablename:@"Resource" withPKName:@"uuid" contextProvider:appDelegate];
    for(;item_index < end_index;item_index++)
    {
        
     
       
        
        Catalog_sub_video *videoData = [videoListAll objectAtIndex:[[NSNumber numberWithInt:item_index] integerValue]];
        
        Resource *resourceData = (Resource*)[dtResource find:videoData.resource_uuid];
        NSString *videoFilePath =  [[AppMain resourceFolderPath] stringByAppendingFormat:@"/%@",resourceData.path];
        
        NSString *sizeInfo = nil;
         NSFileManager *fileManager = [NSFileManager defaultManager];
        if ( [fileManager fileExistsAtPath:videoFilePath]) {
            NSError *attError = nil;
            NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:videoFilePath error:&attError];
            if( attError == nil ) {
                NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
                unsigned long long length = [fileSizeNumber longLongValue];
                float ff = length/(1024*1024.00);
                sizeInfo = [NSString stringWithFormat:@"%0.2fM",ff];
            }
        }
        UIView *itemView = [self itemViewBuilder:videoData.name withCNTitle:videoData.sub_name withVersionId:videoData.version_id withSizeInfo:sizeInfo];
        
        CGRect frame = itemView.frame;
        frame.origin.y = i*(frame.size.height + 15);
        itemView.frame = frame;
        
        [self.recordView addSubview:itemView];
        
        i++;
    }
     [dtResource release];
    
    
    //toggle previous and next button
    self.nextButton.hidden = YES;
    self.previousButton.hidden = YES;
    if ( self.pageIndex > 0) {
        self.previousButton.hidden = NO;
    }
    int totalPage = ceil((float)videoListAll.count/ITEM_PAGE_SIZE);

    if ( self.pageIndex < (totalPage - 1)) {
        self.nextButton.hidden = NO;
    }
    //page info
    if ( totalPage > 0 ) {
        self.pageInfoView.text = [NSString stringWithFormat:@"total %d page %d of %d",videoListAll.count,self.pageIndex+1,totalPage];
    } else {
        self.pageInfoView.text = @"";
    }
    
    [dtVideo release];
}

- (UIView*) itemViewBuilder:(NSString*)title withCNTitle:(NSString*)title_cn withVersionId:(NSNumber*)versionId withSizeInfo:(NSString*)sizeInfo
{
    UIView *itemView = [[UIView alloc] init];
    [itemView setFrame:CGRectMake(0, 0, 950, 100)];

    //Add arrow view
    UIImage *arrowImage = [UIImage imageNamed:@"arrow_right.png"];
    UIImageView *arrowView = [[UIImageView alloc] initWithImage:arrowImage];
    arrowView.frame = itemView.frame;
    arrowView.contentMode = UIViewContentModeScaleToFill;
    [arrowView setFrame:CGRectMake(2, 5, 10, 11)];
    [itemView addSubview:arrowView];
    [arrowView release];
    
    //title view
    UILabel *titleObj = [[UILabel alloc] init];
    titleObj.textAlignment = UITextAlignmentLeft; 
    titleObj.lineBreakMode = UILineBreakModeWordWrap;  
    titleObj.numberOfLines = 0; 
    titleObj.backgroundColor = [UIColor clearColor];
    titleObj.textColor = [UIColor colorWithRed:0 green:255 blue:255 alpha:1.0];
   
    
     CGSize sz = [title sizeWithFont:titleObj.font constrainedToSize:CGSizeMake(600, 1000)];
    [titleObj setFrame:CGRectMake(20, 0, 600, sz.height)];
    titleObj.text = title;
    
    [itemView addSubview:titleObj];
    [titleObj release];
    
    //size info
     UILabel *sizeObj = [[UILabel alloc] init];
    sizeObj.backgroundColor = [UIColor clearColor];
    sizeObj.textColor = [UIColor colorWithRed:0 green:255 blue:255 alpha:1.0];
    [sizeObj setFrame:CGRectMake(850, 0, 100, sz.height)];
    if ( sizeInfo  != nil ) {
        sizeObj.text = sizeInfo;
    }else{
         sizeObj.text = @"無";
    }
    [itemView addSubview:sizeObj];
    [sizeObj release];
    //sub title
    UILabel *titleCNObj = [[UILabel alloc] initWithFrame:CGRectMake(20, titleObj.frame.origin.y + titleObj.frame.size.height + 10, 600, 30)];
    titleCNObj.text = title_cn;
     titleCNObj.backgroundColor = [UIColor clearColor];
    titleCNObj.textColor = [UIColor colorWithRed:0 green:255 blue:255 alpha:1.0];
    [itemView addSubview:titleCNObj];
    [titleCNObj release];
    
    //seperate view
    UIView *seperaterView = [[UIView alloc] initWithFrame:CGRectMake(0, titleCNObj.frame.origin.y + titleCNObj.frame.size.height + 10, itemView.frame.size.width, 1)];
    [seperaterView setBackgroundColor:[UIColor colorWithRed:0 green:255 blue:255 alpha:0.3]];
    [itemView addSubview:seperaterView];
    [seperaterView release];
    
    //Add button
    if ( sizeInfo  != nil ) {
    UIButton *playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    playButton.frame = itemView.frame;
    playButton.tag = [versionId intValue];
    [playButton addTarget:self action:@selector(playVideo:) forControlEvents:UIControlEventTouchUpInside];
    [itemView addSubview:playButton];
    }
   // [playButton release];
    
    return [itemView autorelease];
}
- (void) playVideo:(UIButton*)sender
{
    int video_version_id = sender.tag;
    clublbizaAppDelegate *appDelegate = (clublbizaAppDelegate *)[[UIApplication sharedApplication] delegate];

    TMDataTable *dtVideo = [[TMDataTable alloc] initWithTablename:@"Catalog_sub_video" withPKName:@"uuid" contextProvider:appDelegate];
    Catalog_sub_video *videoData = (Catalog_sub_video*)[dtVideo findByField:@"version_id" withValue:[NSNumber numberWithInt:video_version_id] withSort:nil];
    
    if ( videoData.resource_uuid.length > 0 ) {
        TMDataTable *dtResource = [[TMDataTable alloc] initWithTablename:@"Resource" withPKName:@"uuid" contextProvider:appDelegate];
        Resource *resourceData = (Resource*)[dtResource find:videoData.resource_uuid];
        NSString *videoFilePath =  [[AppMain resourceFolderPath] stringByAppendingFormat:@"/%@",resourceData.path];
        [dtResource release];
        
        NSURL *videoURL = [NSURL fileURLWithPath:videoFilePath];
        
      

        PlayViewController *mpviewController = [[PlayViewController alloc] initWithNibName:@"PlayViewController" bundle:nil];
        mpviewController.videoListOpener = self;
        [mpviewController play:videoURL];
        [self presentModalViewController:mpviewController animated:NO];
        
       
    }
   
    
    [dtVideo release];
    
    
}

- (IBAction)previousPage:(id)sender
{
    self.pageIndex -= 1;
    [self refreshDataListView];
}
- (IBAction)nextPage:(id)sender
{
    self.pageIndex += 1;
    [self refreshDataListView];

}

- (void) refreshBackGrounImage
{
    NSString *defaultKeyName = APPLICATION_BACKGROUND_IMAGE_NAME_3;
    
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *isCustomize = [userDefaults stringForKey:defaultKeyName];
    if (isCustomize != nil){
        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        
        
        NSString *bgImgPath = [documentsPath stringByAppendingFormat:@"/%@",defaultKeyName];
        UIImage *image = [UIImage imageWithContentsOfFile:bgImgPath];
        self.mainBackgroundImage.image = image;
    }else {
        UIImage *image = [UIImage imageNamed:@"bg3.jpg"];
        self.mainBackgroundImage.image = image;
    }
}
@end
